const express = require('express');
const router = express.Router();
const utility = require('utility')
const db = require('../utils/db');

router.get('/userinfo', async(req, res) => {
    // console.log(req.user);
    let r = await db('select * from user where id = ?', req.user.id);
    if (r && r.length > 0) {
        res.send({
            status: 0,
            message: '获取成功',
            data: r[0]
        })
    }
});
router.post('/userinfo', async(req, res) => {
    if (req.body.id != req.user.id) {
        res.send({
            status: 1,
            message: 'id错误，重新登录',
        })
        return
    }
    let r = await db('update user set ? where id = ?', [req.body, req.user.id]);
    // console.log(r)
    if (r && r.affectedRows > 0) {
        res.send({
            status: 0,
            message: '信息修改成功'
        });
    } else {
        res.send({
            status: 1,
            message: '信息修改失败'
        });
    };
});
router.post('/updatepwd', async(req, res) => {
    let newpassword = utility.md5(req.body.newPwd);
    let oldpassword = utility.md5(req.body.oldPwd);
    if (oldpassword == newpassword) {
        res.send({ status: 1, message: '新旧密码不能一致' });
    };
    let r1 = await db('select password from user where id = ?', req.user.id);
    // console.log(r1[0].password)
    if (r1[0].password != oldpassword) {
        res.send({
            status: 1,
            message: '原密码输入不正确'
        })
    } else {
        let r2 = await db('update user set password = ? where id = ?', [newpassword, req.user.id]);
        if (r2 && r2.affectedRows > 0) {
            res.send({
                status: 0,
                message: '修改成功'
            })
        } else {
            res.send({
                status: 1,
                message: '修改失败'
            })
        }
    }
});
router.post('/update/avatar', async(req, res) => {
    // console.log(req.body.avatar)
    let r = await db('update user set user_pic = ? where id=?', [req.body.avatar, req.user.id]);
    if (r && r.affectedRows > 0) {
        res.send({ status: 0, message: '更新头像成功' });
    } else {
        res.send({ status: 1, message: '更新头像失败' });
    }
});
module.exports = router;